<?php
// +----------------------------------------------------------------------
// | Description: Comments
// +----------------------------------------------------------------------
// | Author: orchief
// +----------------------------------------------------------------------
// | Date: 2018-02-01 17:15:14
// +----------------------------------------------------------------------

namespace app\client\controller;

use app\common\controller\Rest;
use app\client\model\Member;
use app\client\model\Product;
use app\client\model\OrdersItem;


class Comments extends Rest
{
    public $modelName = 'Comment';
    public function index()
    {
        if($this->isClient){
            $data = self::$model->getClientDataList();
        }else{
            $data = self::$model->getDataList();
        }
        $this->jsonData($data, self::$model -> getError());
    }

    public function save()
    {
        $Product = new Product();
            
        switch($this -> param['ReviewMark']){
            case 1:
                $field = 'One';
            break;
            case 2:
                $field = 'Two';
            break;
            case 3:
                $field = 'Three';
            break;
            case 4:
                $field = 'Four';
            break;
            default:
                $field = 'Five';
        }
        self::$model -> startTrans();
        try{
            $Product ->where(['Id' => $this -> param['ProductId']])-> setInc($field, 1);
            $members = new Member();
            $userInfo = $members -> get($this -> param['UserId']);
            $this -> param['UserName'] = $userInfo['UserName'];

            // 如果是发表评论 则修改订单相应状态
            $OrdersItem = new OrdersItem();
            $OrdersItem 
            -> where(['OrderId' => $this->param['OrderId'], 'ProductId' => $this->param['ProductId'], 'SkuId' => $this->param['SkuId'] ])
            -> update(['IsRated' => 1]);
            $res = self::$model->createData($this->param);
            self::$model -> commit();
        }catch(\Exception $e){
            self::$model -> rollback();
            $this -> abort(false, '评论发表失败!');
        }
        
        $this->checkRes($res, '评论发表成功', self::$model->getError());
    }

    public function update()
    {
        $fields = 'ReviewContent,ReviewMark,ReplyContent,ReplyDate,IsHidden';   // 可操作字段
        if($this -> param['ReplyContent']){
            $this -> param['ReplyDate'] = date("Y-m-d H:i:s");  // 如果有回复内容则是回复的  自动填上回复时间
        }
        $res = self::$model->updateDataById($this->param, $this->param['id'], $fields);
        $this->checkRes($res, '编辑成功', self::$model->getError());
    }
}
